<template>
  <el-main>
    <el-card style="margin-bottom: 20px; display: flex; align-items: center">
      <!-- 查询条件 -->
      <el-form :model="searchModel" ref="searchForm" label-width="80px" :inline="true" style="display: flex; align-items: center">
        <el-form-item>
          <el-input v-model="searchModel.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" round icon="el-icon-search">查询</el-button>
          <el-button type="primary" round icon="el-icon-plus" @click="dialogFormVisible = true">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->

    <el-table stripe :data="roleList" style="width: 100%; margin-bottom: 10px; text-align: center">
      <el-table-column prop="No" label="序号" width="80" align="center" header-align="center">
        <template slot-scope="scope">
          {{ (roleVo.pageNo - 1) * roleVo.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="id" label="角色id" width="auto" align="center" header-align="center"></el-table-column>
      <el-table-column prop="role" label="角色名称" width="auto" align="center" header-align="center"></el-table-column>
      <el-table-column label="操作" width="400px" align="center" header-align="center" fixed="right">
        <template slot-scope="scope">
          <el-button icon="el-icon-setting" type="primary" size="small" @click="assignRole_1(scope.row)">分配权限</el-button>
          <el-button icon="el-icon-edit" type="primary" size="small" @click="openAddUI(scope.row)">修改</el-button>
          <el-button icon="el-icon-delete" type="danger" size="small" @click="delRole(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页工具栏 -->
    <el-pagination
      :current-page.sync="roleVo.pageNo"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="roleVo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="roleVo.total"
      style="margin-top: 15px"
      @size-change="assignSizeChange"
      @current-change="assignCurrentChange"
    />

    <!-- 新增弹窗 -->
    <el-dialog :visible.sync="dialogFormVisible" :title="title" center @close="closeAddUI">
      <el-form :model="roleForm">
        <el-form-item label="角色名称" label-width="100px">
          <el-input v-model="roleForm.name" autocomplete="off" placeholder="请输入角色名称" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="roleAdd(roleForm)">确定</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改弹窗 -->
    <el-dialog :visible.sync="updateDialogVisible" :title="title" center @close="closeAddUI">
      <el-form :model="updateForm">
        <el-form-item label="角色名称" label-width="100px">
          <el-input v-model="updateForm.role" autocomplete="off" placeholder="请输入角色名称" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="roleUpdate(updateForm)">确定</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色窗口 -->
    <el-dialog :title="assignDialog.title" center :visible.sync="assignDialog.visible" @Close="onAssignClose">
      <el-tree
        ref="assignTree"
        :data="assignTreeData"
        node-key="id"
        :props="defaultProps"
        emty-text="暂无数据"
        :show-checkbox="true"
        :highlight-current="true"
        default-expand-all
      ></el-tree>
      <div style="text-align: right; margin-top: 20px">
        <el-button type="primary" @click="assignDialog.visible = false">确定</el-button>
        <el-button @click="assignDialog.visible = false">取消</el-button>
      </div>
    </el-dialog>
  </el-main>
</template>

<script>
import adminApi from '@/api/adminManager'
import roleApi from '@/api/role'
import leafUtils from '@/utils/leaf'
export default {
  name: 'index',
  data() {
    return {
      title: '新增角色',
      dialogFormVisible: false,
      updateDialogVisible: false,
      //查询条件
      searchModel: {
        roleName: '',
      },
      roleList: [], //角色列表

      //角色对象
      roleVo: {
        pageNo: 1,
        pageSize: 5,
        userId: '',
        total: 0,
      },
      roleForm: {},
      updateForm: {},

      //权限窗口
      assignDialog: {
        title: '',
        visible: false,
      },
      roleId: '',
      assignTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
    }
  },

  methods: {
    //获取角色列表
    getAssignRoleList(pageNo = 1, pageSize = 5) {
      this.roleVo.userId = this.$store.getters.userId
      this.roleVo.pageNo = pageNo
      this.roleVo.pageSize = pageSize

      adminApi.getAssignRoleList(this.roleVo).then((response) => {
        this.roleList = response.e.records
        this.roleVo.total = response.e.total
      })
    },

    //增加角色
    roleAdd(form) {
      console.log(form)
      roleApi.addRole({ role: form.name }).then((response) => {
        this.$message.success('新增角色成功')
        this.getAssignRoleList()
        this.dialogFormVisible = false
      })
    },

    //编辑角色
    roleUpdate(form) {
      roleApi.updateRole({ id: form.id, role: form.role }).then((response) => {
        this.$message.success('修改角色成功')
        this.getAssignRoleList()
        this.updateDialogVisible = false
      })
    },

    //删除角色
    delRole(row) {
      this.$confirm('此操作将删除该角色，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        roleApi.delRole({ id: row.id }).then((response) => {
          this.$message.success('删除成功')
          this.getAssignRoleList()
        })
      })
    },

    //分配权限
    assignRole_1(row) {
      this.roleId = row.id

      let params = { adId: this.$store.getters.userId, roleId: row.id }

      roleApi.getAssignTreeApi(params).then((response) => {
        let { permissionList } = response.e

        let { checkList } = response.e

        console.log(permissionList)
        console.log(checkList)
        let { setLeaf } = leafUtils()

        let newPermissionList = setLeaf(permissionList)

        console.log(newPermissionList)
        this.assignTreeData = newPermissionList
        console.log(this.assignTreeData)
        this.$nextTick(() => {
          let nodes = this.$refs.assignTree.children
          console.log("***")
          console.log(nodes)
          this.setChild(nodes, checkList)
        })
      })

      //显示窗口
      this.assignDialog.visible = true
      //设置窗口标题
      this.assignDialog.title = `给【${row.role}】分配权限`
    },

    setChild(childNodes, checkList) {
      console.log(111)
      //判断是否存在子节点
      if (childNodes && childNodes.length > 0) {
        //循环所有权限
        for (let i = 0; i < childNodes.length; i++) {
          console.log(childNodes[i])
          //根据 data 或者 key 拿到 Tree 组件中的 node
          let node = this.$refs.assignTree.getNode(childNodes[i])
          console.log(node)
          if (!node) {
            console.error(`No node found at index ${childNodes[i]}`)
            // 处理错误，例如向用户显示错误消息
          } else {
            // node 不是 null，继续您的代码
          }
          //判断是否已经拥有对应的角色数据
          if (checkList && checkList.length > 0) {
            // console.log(checkList)
            //循环遍历已有的权限集合
            for (let j = 0; j < checkList.length; j++) {
              //   console.log(checkList[j] + '   ' + childNodes[i].pid)
              //找到已经存在的菜单权限节点
              if (checkList[j] == childNodes[i].pid) {
                console.log(checkList[j] + '   ' + childNodes[i].pid)
                //如果节点是展开状态，则将树节点选中
                if (childNodes[i].open) {
                  console.log(1122222)
                  //   console.log(node)
                  this.$refs.assignTree.setChecked(node, true)
                  break
                }
              }
            }
          }
          if (childNodes[i].children) {
            this.setChild(childNodes[i].children, checkList)
          }
        }
      }
    },
    /**
     * 分配权限窗口取消事件
     */
    onAssignClose() {
      this.assignDialog.visible = false
    },
    /**
     * 分配权限窗口确认事件
     */
    async onAssignConfirm() {},
    // search() {
    //
    // },
    /**
     * 当每页显示数量发生变化时触发
     */
    assignSizeChange(size) {
      this.roleVo.pageSize = size
      this.getAssignRoleList(this.roleVo.pageNo, size)
    },
    /**
     * 当页码发生变化时触发
     */
    assignCurrentChange(page) {
      this.roleVo.pageNo = page
      this.getAssignRoleList(page, this.roleVo.pageSize)
    },
    /**
     * 编辑角色
     */
    handleEdit(row) {},
    /**
     * 删除角色
     */
    handleDelete(row) {},
    /**
     * 分配权限
     */
    assignRole(row) {},
    openAddUI(row) {
      this.updateDialogVisible = true
      this.updateForm = Object.assign({}, row)
    },
    closeAddUI() {
      this.dialogFormVisible = false
      this.roleForm = {
        name: '',
        position: '',
      }
    },
  },
  created() {
    this.getAssignRoleList()
  },
  mounted() {
    //     this.$nextTick(() => {
    //       this.tableHeight = window.innerHeight - 220
    //     })
  },
}
</script>

<style scoped>
</style>
